package com.ruyuan.seckilling.purchase.controller;

import com.ruyuan.seckilling.purchase.async.PurchaseContext;
import com.ruyuan.seckilling.purchase.async.ServletAsyncListener;
import com.ruyuan.seckilling.purchase.async.event.Step1CheckProduct;
import com.ruyuan.seckilling.purchase.request.PurchaseRequest;
import com.ruyuan.starter.async.BossEventBus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.AsyncContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author zhonghuashishan
 */
@Slf4j
@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private BossEventBus bossEventBus;

    @PostMapping
    public void seckillingPurchase(@RequestBody PurchaseRequest request,
                                   HttpServletRequest servletRequest,
                                   HttpServletResponse servletResponse) {
        String validateResult = request.validateParams();
        if (Objects.nonNull(validateResult)) {
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json;charset=UTF-8");
            try (ServletOutputStream out = servletResponse.getOutputStream()) {
                String s = "{\"success\":false, \"info\":\"" + validateResult + "\"}";
                out.write(s.getBytes(StandardCharsets.UTF_8));
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            AsyncContext asyncContext = servletRequest.startAsync();
            asyncContext.setTimeout(5000);
            asyncContext.addListener(new ServletAsyncListener());

            PurchaseContext purchaseContext = new PurchaseContext();
            purchaseContext.setAsyncContext(asyncContext);
            purchaseContext.setActivityId(request.getActivityId());
            purchaseContext.setSkuId(request.getSkuId());
            purchaseContext.setUserId(request.getUserId());

            bossEventBus.publish("step1", new Step1CheckProduct(), purchaseContext);
        }
    }

}
